package com.quan.upms.web.controller;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.quan.base.common.base.web.support.BaseResult;
import com.quan.base.common.base.web.support.controller.BaseController;
import com.quan.base.common.utils.Paginator;
import com.quan.upms.annotation.RequiresPermissions;
import com.quan.upms.rpc.api.UpmsUserService;
import com.quan.upms.rpc.extend.UpmsUserDto;
import com.quan.upms.rpc.model.UpmsUser;

@RestController
@RequestMapping(value = "/api/upms/user")
public class UpmsUserController extends BaseController {

	@Autowired
	private UpmsUserService upmsUserService;
	
	@RequiresPermissions(value="upms:user:add", description="添加用户")
	@PostMapping(value = "/add")
	public Object add(@Valid @RequestBody UpmsUser entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return BaseResult.failure(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		if (null != this.upmsUserService.checkValue("account", entity.getAccount())) {
			return BaseResult.failure("账号已存在");
		}
		if (null != this.upmsUserService.checkValue("email", entity.getEmail())) {
			return BaseResult.failure("邮件地址已存在");
		}
		if (null != this.upmsUserService.checkValue("mobile", entity.getMobile())) {
			return BaseResult.failure("手机号码已存在");
		}
		this.upmsUserService.insertSelective(entity);
		
		return BaseResult.ok();
	}

	@RequiresPermissions(value="upms:user:delete", description="删除用户")
	@GetMapping(value = "/delete/{id}")
	public Object delete(@PathVariable Integer id) {
		this.upmsUserService.delete(id);
		
		return BaseResult.ok();
	}
	
	@RequiresPermissions(value="upms:user:delete", description="批量删除用户")
	@GetMapping(value = "/deleteBatch")
	public Object deleteBatch(String ids) {
		this.upmsUserService.deleteByIds(ids) ;
		
		return BaseResult.ok();
	}
	
	@RequiresPermissions(value="upms:user:update", description="修改用户信息")
	@PostMapping(value = "/update")
	public Object update(@Valid @RequestBody UpmsUser entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return BaseResult.failure(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		UpmsUser oldUser = this.upmsUserService.selectById(entity.getId()) ;
		if(null != oldUser.getAccount() && !oldUser.getAccount().equals(entity.getAccount())) {
			if(null != this.upmsUserService.checkValue("account", entity.getAccount())) {
				return BaseResult.failure("账号已存在");
			}
		}
		if(null != oldUser.getEmail() && !oldUser.getEmail().equals(entity.getEmail())) {
			if(null != this.upmsUserService.checkValue("email", entity.getEmail())) {
				return BaseResult.failure("邮件地址已存在");
			}
		}
		if(null != oldUser.getMobile() && !oldUser.getMobile().equals(entity.getMobile())) {
			if(null != this.upmsUserService.checkValue("mobile", entity.getMobile())) {
				return BaseResult.failure("手机号码已存在");
			}
		}
		this.upmsUserService.updateSelective(entity);
		
		return BaseResult.ok();
	}

	@RequiresPermissions(value="upms:user:detail_base", description="查询用户基本信息")
	@GetMapping(value = "/get/{id}")
	public Object get(@PathVariable Integer id) {
		return this.upmsUserService.selectById(id);
	}
	
	@RequiresPermissions(value="upms:user:detail_all", description="查询用户关联详情")
	@GetMapping(value = "/getUserDetail")
	public Object getUserDetail(Integer id) {
		return this.upmsUserService.getUserDetail(id) ;
	}

	@RequiresPermissions(value="upms:user:list", description="查询用户列表")
	@GetMapping(value = "/list")
	public Object list(UpmsUserDto dto) {
		return this.upmsUserService.selectPage(new Paginator(this.request), dto);
	}
	
	
	
	@RequiresPermissions(value="upms:user:batch_reset_password", description="批量重置用户密码")
	@PostMapping(value = "/batchResetPassword")
	public Object batchResetPassword(@RequestBody List<Integer> ids) {
		this.upmsUserService.batchResetPassword(ids.toArray(new Integer[ids.size()]));
		return BaseResult.ok();
	}
	
	@RequiresPermissions(value="upms:user:batch_change_status", description="批量修改用户状态")
	@PostMapping(value = "/batchUpdateStatus")
	public Object batchUpdateStatus(@RequestBody Map<Object, Object> params) {
		JSONArray parseArray = JSON.parseArray(params.get("ids").toString());
		Integer[] ids = parseArray.toArray(new Integer[parseArray.size()]);
		Integer status = (Integer) params.get("status");
		if(null != ids && ids.length > 0) {
			this.upmsUserService.batchUpdateStatus(ids, status);
		} else {
			return BaseResult.failure("请选择需要设置的记录");
		}
		
		return BaseResult.ok();
	}
	
	@RequiresPermissions(value="upms:user:add_user_to_group_assign", description="添加用户到群组")
	@PostMapping(value = "/addUserToGroupAssign")
	public Object addUserToGroupAssign(@RequestBody UpmsUserDto dto) {
		if(null == dto.getUserIds() || dto.getUserIds().isEmpty()) {
			return BaseResult.failure("请选择需要加入组的用户");
		}
		this.upmsUserService.addUsersToGroupAssign(dto);
		return BaseResult.ok();
	}
	
	@RequiresPermissions(value="upms:user:add_user_to_role_assign", description="添加用户到角色")
	@PostMapping(value = "/addUserToRoleAssign")
	public Object addUserToRoleAssign(@RequestBody UpmsUserDto dto) {
		if(null == dto.getUserIds() || dto.getUserIds().isEmpty()) {
			return BaseResult.failure("请选择需要加入分配的用户");
		}
		this.upmsUserService.addUsersToRoleAssign(dto);
		return BaseResult.ok();
	}
	
	@RequiresPermissions(value="upms:user:add_user_to_org_assign", description="添加用户到组织机构")
	@PostMapping(value = "/addUserToCompanyDeptAssign")
	public Object addUserToOrganizationAssign(@RequestBody UpmsUserDto dto) {
		if(null == dto.getUserIds() || dto.getUserIds().isEmpty()) {
			return BaseResult.failure("请选择需要加入组织机构的用户");
		}
		this.upmsUserService.addUsersToCompanyDeptAssign(dto);
		return BaseResult.ok();
	}
	
	@RequiresPermissions(value="upms:user:get_user_groups", description="查询用户所属群组")
	@GetMapping(value = "/getUserGroups")
	public Object getUserGroups(Integer id) {
		return this.upmsUserService.getUserGroups(id) ;
	}
	
	@RequiresPermissions(value="upms:user:get_user_roles", description="查询用户角色")
	@GetMapping(value = "/getUserRoles")
	public Object getUserRoles(Integer id) {
		return this.upmsUserService.getUserRoles(id) ;
	}
	
	@RequiresPermissions(value="upms:user:get_user_permission", description="查询用户权限")
	@GetMapping(value = "/getUserPermission")
	public Object getUserPermission(Integer id) {
		return this.upmsUserService.getUserPermission(id) ;
	}
	
	@PostMapping(value = "/getAccount")
	public Object getAccount(String account) {
		return this.upmsUserService.getAccount(account);
	}
	
	/**
	 * 获取个人所属群组，不需权限验证
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/getMyGroups")
	public Object getMyGroups(Integer id) {
		return this.upmsUserService.getUserGroups(id) ;
	}
	
	/**
	 * 获取个人角色，不需权限验证
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/getMyRoles")
	public Object getMyRoles(Integer id) {
		return this.upmsUserService.getUserRoles(id) ;
	}
	
	/**
	 * 获取个人权限，不需权限验证
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/getMyPermission")
	public Object getMyPermission(Integer id) {
		return this.upmsUserService.getUserPermission(id) ;
	}
	
	/**
	 * 修改个人密码，不需权限验证
	 * @param dto
	 * @return
	 */
	@PostMapping(value = "/updateMyPassword")
	public Object updateMyPassword(@RequestBody UpmsUserDto dto) {
		try {
			if(StringUtils.isBlank(dto.getOldPassword())) {
				return BaseResult.failure("原密码不能为空");
			}
			if(StringUtils.isBlank(dto.getNewPassword())) {
				return BaseResult.failure("新密码不能为空");
			}
			this.upmsUserService.updatePassword(dto.getId(), dto.getOldPassword(), dto.getNewPassword()) ;
			return BaseResult.ok();
		} catch (RuntimeException e) {
			return BaseResult.failure(e.getMessage());
		}
	}
	
	/**
	 * 修改个人头像，不需权限验证
	 * @param entity
	 * @return
	 */
	@PostMapping(value = "/updateMyAvatar")
	public Object updateAvatar(@RequestBody UpmsUser entity) {
		this.upmsUserService.updateSelective(entity);
		
		return BaseResult.ok();
	}

	/**
	 * 修改个人基本信息
	 * @param entity
	 * @return
	 */
	@PostMapping(value = "/updateMyInfo")
	public Object updateMyInfo(@RequestBody UpmsUser entity) {
		if (StringUtils.isBlank(entity.getAccount())) {
			return BaseResult.failure("账号不能为空");
		}
		if (StringUtils.isBlank(entity.getEmail())) {
			return BaseResult.failure("邮件地址不能为空");
		}
		if (StringUtils.isBlank(entity.getMobile())) {
			return BaseResult.failure("手机号码不能为空");
		}
		UpmsUser oldUser = this.upmsUserService.selectById(entity.getId()) ;
		if(null != oldUser.getAccount() && !oldUser.getAccount().equals(entity.getAccount())) {
			if(null != this.upmsUserService.checkValue("account", entity.getAccount())) {
				return BaseResult.failure("账号已存在");
			}
		}
		if(null != oldUser.getEmail() && !oldUser.getEmail().equals(entity.getEmail())) {
			if(null != this.upmsUserService.checkValue("email", entity.getEmail())) {
				return BaseResult.failure("邮件地址已存在");
			}
		}
		if(null != oldUser.getMobile() && !oldUser.getMobile().equals(entity.getMobile())) {
			if(null != this.upmsUserService.checkValue("mobile", entity.getMobile())) {
				return BaseResult.failure("手机号码已存在");
			}
		}
		this.upmsUserService.updateSelective(entity);
		
		return BaseResult.ok();
	}
	
}
